package com.wzy.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzy.ucenter.feignclint.CheckCodeClient;
import com.wzy.ucenter.mapper.XcUserMapper;
import com.wzy.ucenter.model.dto.AuthParamsDto;
import com.wzy.ucenter.model.dto.XcUserExt;
import com.wzy.ucenter.model.po.XcUser;
import com.wzy.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author wzy
 * @Date 2024/1/29 15:17
 * @description: 账号密码认证
 */
@Service("password_authService")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //校验验证码
        String checkcodekey = authParamsDto.getCheckcodekey();//验证码标识key
        String checkcode = authParamsDto.getCheckcode();//验证码
        if(StringUtils.isBlank(checkcode)||StringUtils.isBlank(checkcodekey)){
            throw new RuntimeException("验证码不能为空");
        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if(!verify){
            throw  new RuntimeException("验证码不正确");
        }
        //账号是否存在
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, authParamsDto.getUsername()));
        if(xcUser==null){
            throw new RuntimeException("账号不存在");
        }
        //验证密码是否正确
        //用户正确密码
        String passwordDb = xcUser.getPassword();
        //用户输入密码
        String inputPassword = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(inputPassword, passwordDb);
        if(!matches){
            throw new RuntimeException("密码错误");
        }
        XcUserExt userExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,userExt);
        return userExt;
    }
}
